package org.example.repeater.message;

import com.github.benmanes.caffeine.cache.Cache;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;

import static org.example.repeater.message.Constant.*;

public class pushChannel {
    private static Cache<String, Object> caffeineCache;
    private static pushChannel INSTANCE=new pushChannel();
    private pushChannel() {}
    public static pushChannel getInstance(Cache<String, Object> caffeine) {
        caffeineCache=caffeine;
        return INSTANCE;
    }

    /**
     * 获取上级channel
     * @param sim
     * @param ctx
     * @return
     */
    public List<ChannelHandlerContext> getClientContext(String sim, ChannelHandlerContext ctx) {
        List<ChannelHandlerContext> list =new ArrayList<>();
        List<String> findIp = findCtxByIp(sim);
        findIp.forEach(ip->{
            caffeineCache.put(devicePref+ip,ctx);
            ChannelHandlerContext clientContext = (ChannelHandlerContext) caffeineCache.getIfPresent(clientPref + ip);
            if(clientContext!=null) {
                list.add(clientContext);
            }
        });
        return list;
    }



    /***
     * 通过sim 查询ip
     * @param sim
     * @return
     */
    public List<String> findCtxByIp(String sim){
        List<String> list = new ArrayList<>();
        caffeineCache.asMap().forEach((key, value) -> {
            if (key.contains(dataPref)) {
                ((List<String>)value).stream()
                        .filter(simNo->simNo.equals(sim))
                        .forEach(ip->list.add(key.replace(dataPref, "")));
            }
        });
        return list;
    }



}
